//
//  SAAddInventoryVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/6/17.
//

#import "SAAddInventoryVC.h"
#import "SAInventoryListVC.h"
#import "SASearchStoreUserView.h"
#import "SAStoreUserModel.h"
#import "SASystemEmpDetailAPI.h"
#import "SAAddInventoryCell.h"
#import "SACommodityWarehousingHeaderView.h"
#import "SASalesOrderViewListModel.h"
#import "SAWarehousingSelectShopVC.h"
#import "SAWarehousePurchaseFindProductAPI2.h"
#import "SAWarehousePurchaseFindProductV2API.h"
#import "SACommodityAddShopSizeView.h"
#import "YBImageBrowser.h"
#import "ScanHelper.h"
#import "SASalesOrderStatementErrorView.h"
#import "SASalesOrderStatementErrorModel.h"
#import "NSString+nonce.h"
#import "NSString+MD5.h"
#import "SAStockCheckSaveV2API.h"

@interface SAAddInventoryVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate, UITextFieldDelegate,YBImageBrowserDataSource>

@property (nonatomic, strong) UITextField *remarkTf;
@property (nonatomic, strong) UIButton *empBtn;
@property (nonatomic, strong) SAStoreUserModel *userModel;
@property (nonatomic, strong) SASystemEmpDetailAPI *systemEmpDetailAPI;
@property (nonatomic, strong) UILabel *totalCountLab;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, assign) float tableViewTop;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, strong) SAWarehousePurchaseFindProductAPI2 *warehousePurchaseFindProductAPI;
@property (nonatomic, strong) SAWarehousePurchaseFindProductV2API *warehousePurchaseFindProductV2API;
@property (nonatomic, strong) NSArray *imageList;
@property (nonatomic, assign) BOOL isWarehousingStock;//yes可以负数盘点 no不可以负数盘点
@property (nonatomic, strong) SAStockCheckSaveV2API *stockCheckSaveV2API;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, strong) NSString *randomStr;

@end

@implementation SAAddInventoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemEmpDetailAPI == api) {
        self.userModel = [SAStoreUserModel mj_objectWithKeyValues:data[@"data"]];
    }else if (self.warehousePurchaseFindProductAPI == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            
            //如果扫码且只有一个颜色尺码则直接加1处理
            if ([self.warehousePurchaseFindProductAPI.barCodeSign isEqualToString:@"true"]) {
                if (model.targetSkuList.count == 1) {
                    NSString *skuId = model.targetSkuList[0].skuId;
                    model.targetSkuList = [NSMutableArray array];
                    for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                        if ([list.skuId isEqualToString:skuId]) {
                            list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                            list.count = @"0";
                            SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                            list.stock = list.count;
                            
                            newList.colourId = list.colourId;
                            newList.colourName = list.colourName;
                            newList.sizeId = list.sizeId;
                            newList.sizeName = list.sizeName;
                            newList.stock = @"1";
                            newList.count = list.count;
                            newList.skuId = list.skuId;
                            newList.price = model.retailPrice;
                            newList.inventoryCount = list.inventoryCount;
                            [model.targetSkuList addObject:newList];
                        }
                    }
                    [self combinationData:model];
                    [self.tableView reloadData];
                    [self upData];
                    [self setBottomUI];
                    return;
                }
            }
            
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                list.count = @"0";
                SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                list.stock = list.count;
                
                newList.colourId = list.colourId;
                newList.colourName = list.colourName;
                newList.sizeId = list.sizeId;
                newList.sizeName = list.sizeName;
                newList.stock = @"0";
                newList.count = list.count;
                newList.skuId = list.skuId;
                newList.inventoryCount = list.inventoryCount;
                [model.targetSkuList addObject:newList];
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isAll = YES;
            addShopSizeView.isWarehousingStock = self.isWarehousingStock;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                model.targetSkuList = [NSMutableArray array];
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock doubleValue] != 0) {
                        [model.targetSkuList addObject:list];
                    }
                }
                if (model.targetSkuList.count == 0) {
                    return;
                }
                [weakSelf combinationData:model];
                [weakSelf.tableView reloadData];
                [weakSelf upData];
                [weakSelf setBottomUI];
            };
        }else {
            [Prompt popPromptViewWithMsg:@"未查询到商品" duration:2];
        }
    }else if (self.stockCheckSaveV2API == api) {
        [self.dataMarr removeAllObjects];
        self.remarkTf.text = @"";
        [self.tableView reloadData];
        [self upData];
        [self setBottomUI];
        [Prompt popPromptViewWithMsg:@"“单据保存成功”生成未处理盘点单据" duration:2];
    }else if (self.warehousePurchaseFindProductV2API == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                list.inventoryCount = [NSString stringWithFormat:@"%@",list.count];
                list.count = @"0";
                SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                list.stock = list.count;
                
                newList.colourId = list.colourId;
                newList.colourName = list.colourName;
                newList.sizeId = list.sizeId;
                newList.sizeName = list.sizeName;
                newList.stock = @"0";
                newList.count = list.count;
                newList.skuId = list.skuId;
                newList.inventoryCount = list.inventoryCount;
                [model.targetSkuList addObject:newList];
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isAll = YES;
            addShopSizeView.isWarehousingStock = self.isWarehousingStock;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                model.targetSkuList = [NSMutableArray array];
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock doubleValue] != 0) {
                        [model.targetSkuList addObject:list];
                    }
                }
                [weakSelf combinationData:model];
                [weakSelf.tableView reloadData];
                [weakSelf upData];
                [weakSelf setBottomUI];
            };
        }else {
            [Prompt popPromptViewWithMsg:@"未查询到商品" duration:2];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.stockCheckSaveV2API == api) {
        NSDictionary *dict = error.userInfo;
        if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"20007"]) {
            NSDictionary *errorDic = [self dictionaryWithJsonString:dict[@"msg"]];
            NSMutableArray *errorArray = [NSMutableArray array];
            for (NSArray *errorLsit in errorDic) {
                SASalesOrderStatementErrorModel *model = [SASalesOrderStatementErrorModel mj_objectWithKeyValues:errorLsit];
                NSLog(@"%@",model);
                [errorArray addObject:model];
            }
            
            SASalesOrderStatementErrorView *screenView = [SASalesOrderStatementErrorView shareCornView];
            screenView.removeBlock = ^(NSArray * _Nonnull array) {
                for (SASalesOrderViewListModel *model in self.dataMarr) {
                    for (SASalesOrderToPendSkuList *skuList in [model.targetSkuList reverseObjectEnumerator]) {
                        for (SASalesOrderStatementErrorSkuList *errorList in array) {
                            if ([errorList.skuId isEqualToString:skuList.skuId]) {
                                [model.targetSkuList removeObject:skuList];
                                break;
                            }
                        }
                    }
                }
                
                NSMutableArray *newDataArray = [NSMutableArray array];
                for (SASalesOrderViewListModel *listModel in self.dataMarr) {
                    if (listModel.targetSkuList.count > 0) {
                        [newDataArray addObject:listModel];
                    }
                }
                self.dataMarr = newDataArray;
                [self upData];
                [self setBottomUI];
                [self.tableView reloadData];
            };
            [screenView loadData:errorArray];
            [screenView showView:nil];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50001"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self.dataMarr removeAllObjects];
            self.remarkTf.text = @"";
            [self.tableView reloadData];
            [self upData];
            [self setBottomUI];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50002"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self.dataMarr removeAllObjects];
            self.remarkTf.text = @"";
            [self.tableView reloadData];
            [self upData];
            [self setBottomUI];
        }else {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].targetSkuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SAAddInventoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAAddInventoryCell" forIndexPath:indexPath];
    cell.isWarehousingStock = self.isWarehousingStock;
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].targetSkuList[indexPath.row];
    cell.model = model;
    cell.inputBlock = ^(NSString * _Nonnull str) {
        model.stock = str;
        [weakSelf upData];
    };
    cell.addBlock = ^{
        NSInteger stock = [model.stock integerValue] + 1;
        model.stock = [NSString stringWithFormat:@"%zd",stock];
        [weakSelf upData];
    };
    cell.cutBlock = ^{
        NSInteger stock = [model.stock integerValue] - 1;
        model.stock = [NSString stringWithFormat:@"%zd",stock];
        [weakSelf upData];
    };
    cell.inputPriceBlock = ^(NSString * _Nonnull str) {
        model.price = [NSString stringWithFormat:@"%0.2f",[str doubleValue] * 100];
        [weakSelf upData];
    };
    cell.deleteBlock = ^{
        
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(35);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == self.dataMarr.count) {
        return [[UIView alloc] initWithFrame:CGRectZero];
    }
    SACommodityWarehousingHeaderView *headerView = [[SACommodityWarehousingHeaderView alloc] initWithReuseIdentifier:@"SACommodityWarehousingHeaderView"];
    __block SASalesOrderViewListModel *dataModel = self.dataMarr[section];
    headerView.model = dataModel;
    WeakSelf
    headerView.deleteBlock = ^{
        [weakSelf.dataMarr removeObject:dataModel];
        [tableView reloadData];
        [weakSelf upData];
        [weakSelf setBottomUI];
    };
    headerView.addBlock = ^{
        weakSelf.warehousePurchaseFindProductV2API.productIds = dataModel.productId;
        [weakSelf.warehousePurchaseFindProductV2API sendRequestToServerWithActivityViewAndMask:GET];
    };
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == self.dataMarr.count) {
        return kScaleNum(0.01);
    }
    return kScaleNum(35);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(1);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASalesOrderViewListModel *model = self.dataMarr[indexPath.section];
    SASalesOrderToPendSkuList *list = model.targetSkuList[indexPath.row];
    WeakSelf
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        if (model.targetSkuList.count == 1) {
            [weakSelf.dataMarr removeObject:model];
            [tableView reloadData];
            [weakSelf upData];
            [weakSelf setBottomUI];
        }else {
            [model.targetSkuList removeObject:list];
            [tableView reloadData];
            [weakSelf upData];
            [weakSelf setBottomUI];
        }
        
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - event
-(void)clickedListBtn {
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *stockCountingDocuments = [NSString stringWithFormat:@"%@",menuList[3][@"perms"][@"stockCountingDocuments"]];
    if ([stockCountingDocuments isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有盘点单据权限,请联系店长添加" duration:2];
        return;
    }
    
    SAInventoryListVC *pushVC = [SAInventoryListVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)clickedUserBtn {
    [self.view endEditing:YES];
    SASearchStoreUserView *searchStoreUserView = [SASearchStoreUserView shareCornView];
    UIViewController *vc = nil;
    [searchStoreUserView showView:vc];
    WeakSelf
    searchStoreUserView.selectBlock = ^(SAStoreUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        if (userModel.mobile.length > 0) {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@(%@)",userModel.empName,userModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@",userModel.empName] forState:UIControlStateNormal];
        }
        CGFloat imageWidth = weakSelf.empBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.empBtn.titleLabel.bounds.size.width;
        weakSelf.empBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.empBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        [weakSelf.empBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    };
}

-(void)upData {
    if (self.dataMarr.count > 0) {
        NSInteger num = 0;
        for (SASalesOrderViewListModel *model in self.dataMarr) {
            for (SASalesOrderToPendSkuList *list in model.targetSkuList) {
                num += [list.stock integerValue];
            }
        }
        self.totalCountLab.text = [NSString stringWithFormat:@"已盘:%zd款,%zd件",self.dataMarr.count, num];
    }else {
        self.totalCountLab.text = @"";
    }
}

-(void)setBottomUI {
    if (self.dataMarr.count > 0) {
        self.tableView.hidden = NO;
        self.scanBtn.frame = CGRectMake(kScaleNum(76), kScreenHeight - kScaleNum(102) - SafeFooterHeight, kScaleNum(53), kScaleNum(52));
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), kScreenHeight - kScaleNum(102) - SafeFooterHeight, kScaleNum(53), kScaleNum(52));
        self.saveBtn.hidden = NO;
    }else {
        self.tableView.hidden = YES;
        self.scanBtn.frame = CGRectMake(kScaleNum(76),  self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(52));
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(52));
        self.saveBtn.hidden = YES;
        self.randomStr = [NSString random:10];
    }
    [self.tableView reloadData];
}

-(void)clickedScanBtn {
    [self.view endEditing:YES];
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        self.warehousePurchaseFindProductAPI.barCodeSign = @"true";
        self.warehousePurchaseFindProductAPI.productCodeOrBar = result;
        [self.warehousePurchaseFindProductAPI sendRequestToServerWithActivityViewAndMask:GET];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

-(void)clickedAddBtn {
    [self.view endEditing:YES];
    SAWarehousingSelectShopVC *shopVC = [[SAWarehousingSelectShopVC alloc] initWithSelectMarr:[NSMutableArray array]];
    shopVC.isWarehousingStock = self.isWarehousingStock;
    [self.navigationController pushViewController:shopVC animated:YES];
    WeakSelf
    shopVC.selectBlock = ^(NSMutableArray<SASalesOrderViewListModel *> * _Nonnull selectMarr) {
        for (SASalesOrderViewListModel *model in selectMarr) {
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                if ([list.stock doubleValue] != 0) {
                    list.inventoryCount = list.count;
                    [model.targetSkuList addObject:list];
                }
            }
            [weakSelf combinationData:model];
        }
    };
}

-(void)combinationData:(SASalesOrderViewListModel *)model {
    BOOL newProduct = YES;
    SASalesOrderViewListModel *oldModel = nil;
    for (SASalesOrderViewListModel *listModel in self.dataMarr) {
        if ([listModel.productId isEqualToString:model.productId]) {
            oldModel = listModel;
            newProduct = NO;
            break;
        }
    }
    if (newProduct) {
        for (SASalesOrderToPendSkuList *skuModel in model.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
        }
        [self.dataMarr addObject:model];
    }else {
        for (SASalesOrderToPendSkuList *skuModel in oldModel.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
        }
        for (SASalesOrderToPendSkuList *skuModel in model.targetSkuList) {
            if ([skuModel.stock integerValue] < 0) {
                skuModel.type = 1;
            }else {
                skuModel.type = 0;
            }
            BOOL newSku = YES;
            for (SASalesOrderToPendSkuList *model2 in oldModel.targetSkuList) {
                if ([skuModel.skuId isEqualToString:model2.skuId] && skuModel.type == model2.type) {
                    newSku = NO;
                    model2.stock = [NSString stringWithFormat:@"%zd",[model2.stock integerValue] + [skuModel.stock integerValue]];
                    break;
                }
            }
            if (newSku) {
                [oldModel.targetSkuList addObject:skuModel];
            }
        }
    }
    [self upData];
    [self setBottomUI];
}

//防止多次结单
- (void)unisversalButtonAcrion:(UIButton *)sender
{
    sender.userInteractionEnabled = NO;
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(clickedSaveBtn) object:sender];
    [self performSelector:@selector(clickedSaveBtn) withObject:sender afterDelay:0.3f];
}

-(void)clickedSaveBtn {
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    NSMutableArray *productSkuFormArr = [NSMutableArray array];
    mdic[@"productSkuForms"] = productSkuFormArr;
    NSInteger afterStock = 0;
    NSInteger beforeStock = 0;
    for (SASalesOrderViewListModel *detailModel in self.dataMarr) {
        NSMutableDictionary *skuMdic = [NSMutableDictionary dictionary];
        skuMdic[@"productCode"] = detailModel.productCode;
        skuMdic[@"productId"] = detailModel.productId;
        skuMdic[@"productName"] = detailModel.productName;
        NSMutableArray *skuMarr = [NSMutableArray array];
        skuMdic[@"skuForms"] = skuMarr;
        [productSkuFormArr addObject:skuMdic];
        
        for (SASalesOrderToPendSkuList *model in detailModel.targetSkuList) {
            afterStock += [model.stock integerValue];
            beforeStock += [model.inventoryCount integerValue];
            NSMutableDictionary *skuFormMdic = [NSMutableDictionary dictionary];
            skuFormMdic[@"afterStock"] = model.stock;
            skuFormMdic[@"beforeStock"] = model.inventoryCount;
            skuFormMdic[@"colourId"] = model.colourId;
            skuFormMdic[@"colourName"] = model.colourName;
            skuFormMdic[@"diffStock"] = [NSString stringWithFormat:@"%zd",[model.stock integerValue] - [model.inventoryCount integerValue]];
            skuFormMdic[@"sizeId"] = model.sizeId;
            skuFormMdic[@"sizeName"] = model.sizeName;
            skuFormMdic[@"skuId"] = model.skuId;
            [skuMarr addObject:skuFormMdic];
        }
    }
    
    mdic[@"checkEmpId"] = self.userModel.empId;
    mdic[@"totalAfterStock"] = [NSString stringWithFormat:@"%zd",afterStock];
    mdic[@"totalBeforeStock"] = [NSString stringWithFormat:@"%zd",beforeStock];
    mdic[@"totalDiffStock"] = [NSString stringWithFormat:@"%zd",afterStock - beforeStock];
    mdic[@"remark"] = self.remarkTf.text;
    
    NSData *nData = [NSJSONSerialization dataWithJSONObject:mdic options:0 error:nil];
    mdic[@"randomStr"] = [NSString stringWithFormat:@"%@%@",self.randomStr,[NSString getMD5WithData:nData]];
    
    self.stockCheckSaveV2API.coverParameters = mdic;
    [self.stockCheckSaveV2API sendRequestToServerWithActivityViewAndMask:POST];
    self.saveBtn.userInteractionEnabled = YES;
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"新增盘点"];
    [self setBgImage:nil];
    self.view.backgroundColor = kBgColor;
    self.isWarehousingStock = YES;
    self.randomStr = [NSString random:10];
    
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [listBtn setImage:[UIImage imageNamed:@"shopSale_list"] forState:UIControlStateNormal];
    [listBtn addTarget:self action:@selector(clickedListBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[listBtn]];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 112)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    
    SAUserInfo *model = [SAValueManger shareInStance].userInfo;
    NSArray *nameArr = @[@"  店员", @"  备注"];
    NSArray *imageArr = @[@"Sale_user", @"Warehousing_icon_5"];
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [titleBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        titleBtn.frame = SARectMake(20, StatusHeight + i * 38, 120, 37);
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.view addSubview:titleBtn];
        
        if (i < 1) {
            UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
            rightBtn.frame = SARectMake(0, StatusHeight + i * 38, kBaseScreenWidth - 20, 37);
            rightBtn.titleLabel.font = kFont(15);
            [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
            rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [self.view addSubview:rightBtn];
            [rightBtn setTitle:[NSString stringWithFormat:@"%@(%@)",model.empName,model.mobile] forState:UIControlStateNormal];
            [rightBtn addTarget:self action:@selector(clickedUserBtn) forControlEvents:UIControlEventTouchUpInside];
            self.empBtn = rightBtn;
            
            CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
            CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
            rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
            rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        }
        
        if (i == 1) {
            UITextField *remarkTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
            remarkTf.placeholder = @"请输入备注";
            remarkTf.text = @"";
            remarkTf.font = kFont(15);
            remarkTf.clearButtonMode = UITextFieldViewModeWhileEditing;
            remarkTf.frame = SARectMake(kBaseScreenWidth - 270, StatusHeight + i * 38, 250, 37);
            remarkTf.textAlignment = NSTextAlignmentRight;
            self.remarkTf = remarkTf;
            remarkTf.returnKeyType = UIReturnKeyDone;
            remarkTf.delegate = self;
            [self.view addSubview:remarkTf];
        }
        
        UIView *line = [[UIView alloc] initWithFrame:SARectMake(20, StatusHeight + i * 38 + 37, kBaseScreenWidth - 40, 1)];
        line.backgroundColor = kLineColor;
        [self.view addSubview:line];
    }
    
    UILabel *totalCountLab = [[UILabel alloc] initWithFrame:SARectMake(20, StatusHeight + 2 * 38, 120, 37)];
    totalCountLab.font = kFont(15);
    totalCountLab.textColor = kBlackColor;
    totalCountLab.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:totalCountLab];
    self.totalCountLab = totalCountLab;
    totalCountLab.text = @"已盘:0款,0件";
    
    self.tableViewTop = totalCountLab.maxY;
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [saveBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
    saveBtn.frame = CGRectMake(0, kScreenHeight - kScaleNum(40) - SafeFooterHeight, kScreenWidth, kScaleNum(40) + SafeFooterHeight);
    saveBtn.titleLabel.font = kFont(18);
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(unisversalButtonAcrion:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveBtn];
    saveBtn.hidden = YES;
    self.saveBtn = saveBtn;
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setImage:[UIImage imageNamed:@"Sale_scan"] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(kScaleNum(76), totalCountLab.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(52));
    scanBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    self.scanBtn = scanBtn;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"Sale_Add"] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), totalCountLab.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(52));
    addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    self.addBtn = addBtn;
    
    self.systemEmpDetailAPI.empId = model.empId;
    [self.systemEmpDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
}

#pragma mark - lazy
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.tableViewTop, kScreenWidth, kScreenHeight - kScaleNum(112) - SafeFooterHeight - self.tableViewTop) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.hidden = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAAddInventoryCell class] forCellReuseIdentifier:@"SAAddInventoryCell"];
        [_tableView registerClass:[SACommodityWarehousingHeaderView class] forHeaderFooterViewReuseIdentifier:@"SACommodityWarehousingHeaderView"];
    }
    return _tableView;
}

-(UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(35))];
        
        UIView *whireView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(35))];
        whireView2.backgroundColor = kTextBgColor;
        [_headerView addSubview:whireView2];
        
        UILabel *titleLab2 = [[UILabel alloc] initWithFrame:SARectMake(20, 0, 35, 35)];
        titleLab2.text = @"商品";
        titleLab2.textColor = kGrayColor;
        titleLab2.font = kBFont(14);
        [whireView2 addSubview:titleLab2];
        
        UILabel *titleLab3 = [[UILabel alloc] initWithFrame:SARectMake(136, 0, 60, 35)];
        titleLab3.text = @"当前库存";
        titleLab3.textColor = kGrayColor;
        titleLab3.font = kBFont(14);
        titleLab3.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab3];
        
        UILabel *titleLab4 = [[UILabel alloc] initWithFrame:SARectMake(214, 0, 60, 35)];
        titleLab4.text = @"盘点数";
        titleLab4.textColor = kGrayColor;
        titleLab4.font = kBFont(14);
        titleLab4.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab4];
        
        UILabel *titleLab5 = [[UILabel alloc] initWithFrame:SARectMake(305, 0, 70, 35)];
        titleLab5.text = @"盈亏数";
        titleLab5.textColor = kGrayColor;
        titleLab5.font = kBFont(14);
        titleLab5.textAlignment = NSTextAlignmentCenter;
        [whireView2 addSubview:titleLab5];
    }
    return _headerView;
}

-(SASystemEmpDetailAPI *)systemEmpDetailAPI {
    if (!_systemEmpDetailAPI) {
        _systemEmpDetailAPI = [SASystemEmpDetailAPI apiWithDelegate:self];
    }
    return _systemEmpDetailAPI;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SAWarehousePurchaseFindProductAPI2 *)warehousePurchaseFindProductAPI {
    if (!_warehousePurchaseFindProductAPI) {
        _warehousePurchaseFindProductAPI = [SAWarehousePurchaseFindProductAPI2 apiWithDelegate:self];
    }
    return _warehousePurchaseFindProductAPI;
}

-(SAWarehousePurchaseFindProductV2API *)warehousePurchaseFindProductV2API {
    if (!_warehousePurchaseFindProductV2API) {
        _warehousePurchaseFindProductV2API = [SAWarehousePurchaseFindProductV2API apiWithDelegate:self];
    }
    return _warehousePurchaseFindProductV2API;
}

-(SAStockCheckSaveV2API *)stockCheckSaveV2API {
    if (!_stockCheckSaveV2API) {
        _stockCheckSaveV2API = [SAStockCheckSaveV2API apiWithDelegate:self];
    }
    return _stockCheckSaveV2API;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
